import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_learn_vi/src/bean/bean_category.dart';
import 'package:flutter_learn_vi/src/net/dio_utils.dart';
import 'package:flutter_learn_vi/src/page/common/common_loading_dialog.dart';
import 'package:flutter_learn_vi/src/page/common/common_nodata_widget.dart';
import 'package:flutter_learn_vi/src/page/topic/topic_details_page.dart';
import 'package:flutter_learn_vi/src/page/topic/topic_enum.dart';
import 'package:flutter_learn_vi/src/utils/log_util.dart';
import 'package:flutter_learn_vi/src/utils/navigator_utils.dart';

/// 创建人： Created by zhaolong
/// 创建时间：Created by  on 2021/1/24.
///
/// 可关注公众号：我的大前端生涯   获取最新技术分享
/// 可关注网易云课堂：https://study.163.com/instructor/1021406098.htm
/// 可关注博客：https://blog.csdn.net/zl18603543572
///
/// 代码清单
///代码清单
class MyErrorPage extends StatefulWidget {
  @override
  _MyErrorPageState createState() => _MyErrorPageState();
}

class _MyErrorPageState extends State<MyErrorPage> {
  @override
  void initState() {
    super.initState();
    Future.delayed(Duration.zero, () {
      getErrorInfo();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(""
            "我的错题"),
      ),
      backgroundColor: Colors.white,

      ///填充布局
      body: Container(
        width: double.infinity,
        height: double.infinity,
        child: RefreshIndicator(
          notificationPredicate: (ScrollNotification notifation) {
            //该属性包含当前ViewPort及滚动位置等信息
            ScrollMetrics scrollMetrics = notifation.metrics;
            if (scrollMetrics.minScrollExtent == 0) {
              return true;
            } else {
              return false;
            }
          },
          onRefresh: () async {
            await getErrorInfo();
            return true;
          },
          child: NestedScrollView(
            body: buildListView(),
            headerSliverBuilder:
                (BuildContext context, bool innerBoxIsScrolled) {
              return [
                SliverToBoxAdapter(
                  child: Container(
                    padding: EdgeInsets.all(12),
                    width: double.infinity,
                    child: Card(
                      child: Container(
                        padding: EdgeInsets.all(10),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            Text(
                              "错题移除规则",
                              style: TextStyle(
                                  fontWeight: FontWeight.w500,
                                  fontSize: 14,
                                  color: Colors.black),
                            ),
                            SizedBox(
                              height: 10,
                            ),
                            Text(
                              "$_errorRules",
                              style: TextStyle(
                                  fontWeight: FontWeight.w500,
                                  fontSize: 14,
                                  color: Colors.red),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ),
                )
              ];
            },
          ),
        ),
      ),
    );
  }

  Widget buildListView() {
    return buildErrorList();
  }

  buildErrorList() {
    if (_categoryBeanList == null) {
      return LoadingWidget();
    }
    if (_categoryBeanList.length == 0) {
      return Center(
          child: NoDataWidget(
        text: "您暂无错哦",
      ));
    }
    return ListView.separated(
      itemCount: _categoryBeanList.length,
      itemBuilder: (BuildContext context, int index) {
        CategoryBean bean = _categoryBeanList[index];
        return InkWell(
          onTap: () {
            NavigatorUtils.pushPage(
              context,
              TopicDetilsPage(
                categoryOne: bean.categoryValue,
                categoryTwo: bean.categoryTwo,
                pageTitle: "我的错题",
                topicEnum: TopicEnum.myError,
              ),
            );
          },
          child: Container(
              padding: EdgeInsets.only(left: 14, right: 14),
              alignment: Alignment.centerLeft,
              child: Row(
                children: [
                  Container(
                    width: 16,
                    height: 16,
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                        color: Colors.red[900],
                        borderRadius: BorderRadius.all(Radius.circular(16))),
                    child: Text(
                      "${index + 1}",
                      maxLines: 1,
                      overflow: TextOverflow.clip,
                      style: TextStyle(fontSize: 10, color: Colors.white),
                    ),
                  ),
                  SizedBox(
                    width: 10,
                  ),
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        Row(
                          children: [
                            Text("${bean.categoryName}"),
                          ],
                        ),
                        SizedBox(
                          height: 6,
                        ),
                        Text("当前错题数量 ${bean.number}"),
                      ],
                    ),
                  ),
                  Icon(
                    Icons.arrow_forward_ios_rounded,
                    size: 18,
                  ),
                ],
              )),
        );
      },
      separatorBuilder: (BuildContext context, int index) {
        return Divider();
      },
    );
  }

  List<CategoryBean> _categoryBeanList;
  String _errorRules = "";

  Future<bool> getErrorInfo() async {
    //post请求发送
    ResponseInfo responseInfo = await DioUtils.instance
        .getRequest(url: HttpHelper.allCategoryUrl, queryParameters: {
      "numberType": "WRONG",
    });

    //登录成功
    if (responseInfo.success) {
      List list = responseInfo.data;
      _categoryBeanList = [];
      if (list != null) {
        list.forEach((element) {
          CategoryBean categoryBean = CategoryBean.fromJson(element);
          _categoryBeanList.add(categoryBean);
        });
      }
    } else {
      _categoryBeanList = [];
      LogUtils.e("获取错题分类失败");
    }

    ResponseInfo errorRules = await DioUtils.instance
        .getRequest(url: HttpHelper.wrongRules, queryParameters: {});
    //错题移除规则
    if (errorRules.success) {
      _errorRules = errorRules.data;
    }
    if (mounted) {
      setState(() {});
    }
    return true;
  }
}
